package com.example.myapplication.picUtils

import android.Manifest
import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.provider.OpenableColumns
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.GridView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import com.example.myapplication.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.coroutines.resume


class ImagePickerActivity : AppCompatActivity(), OnCameraIconClickListener {
    private val REQUEST_CODE_PREVIEW = 1002 // 定义预览请求码
    private lateinit var gridView: GridView
    private lateinit var adapter: ImageGridAdapter
    private lateinit var doneButton: Button
    private lateinit var previewButton: TextView

    private var showCameraButtonConfig: Boolean = true
    private val selectedImages = mutableListOf<ImageItem>()
    private var maxSelectionCount = 9
    private var enableLubanCompress = true

    private lateinit var requestPermissionLauncher: ActivityResultLauncher<Array<String>>
    private lateinit var takePictureLauncher: ActivityResultLauncher<Uri>
    private val viewModel: ImagePickerViewModel by viewModels() // 获取 ViewModel 实例

    companion object {
        const val EXTRA_SHOW_CAMERA_BUTTON = "show_camera_button"
        const val EXTRA_MAX_SELECTION_COUNT = "max_selection_count"
        const val EXTRA_ENABLE_LUBAN_COMPRESS = "enable_luban_compress"
        const val RESULT_PICKED_IMAGES = "picked_images"
        const val RESULT_COMPRESSED_IMAGES = "compressed_images"

        fun start(
            activity: Activity,
            requestCode: Int,
            maxCount: Int = 9,
            enableCompress: Boolean = true,
            showCamera: Boolean = true
        ) {
            val intent = Intent(activity, ImagePickerActivity::class.java).apply {
                putExtra(EXTRA_MAX_SELECTION_COUNT, maxCount)
                putExtra(EXTRA_ENABLE_LUBAN_COMPRESS, enableCompress)
                putExtra(EXTRA_SHOW_CAMERA_BUTTON, showCamera)
            }
            activity.startActivityForResult(intent, requestCode)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_image_picker) // 确保你有这个布局文件

        maxSelectionCount = intent.getIntExtra(EXTRA_MAX_SELECTION_COUNT, 9)
        enableLubanCompress = intent.getBooleanExtra(EXTRA_ENABLE_LUBAN_COMPRESS, true)
        showCameraButtonConfig = intent.getBooleanExtra(EXTRA_SHOW_CAMERA_BUTTON, true)

        initViews()
        initLaunchers()
        setupPermissions()
    }

    private fun initViews() {
        gridView = findViewById(R.id.image_grid_view)
        doneButton = findViewById(R.id.btn_done_selection)
        previewButton = findViewById(R.id.tv_preview_selection)

        adapter = ImageGridAdapter(
            this,
            mutableListOf(),
            selectedImages,
            maxSelectionCount,
            showCameraButtonConfig,
            { imageItem, isSelected -> handleImageSelection(imageItem, isSelected) },
            this // OnCameraIconClickListener
        )
        gridView.adapter = adapter

        doneButton.setOnClickListener {
            processAndReturnSelectedImages()
        }

        previewButton.setOnClickListener {
            if (selectedImages.isNotEmpty()) {
                ImagePreviewActivity.start(
                    this,
                    REQUEST_CODE_PREVIEW,
                    ArrayList(selectedImages), // 传递当前选中的图片
                    0, // 默认从第一张开始预览，可以根据用户最后点击的图片来定位
                    maxSelectionCount
                )

                Toast.makeText(this, "预览 ${selectedImages.size} 张图片", Toast.LENGTH_SHORT)
                    .show()
            }
        }
        updateDoneButtonState()
    }

    // 处理从 ImagePreviewActivity 返回的结果
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_PREVIEW && resultCode == Activity.RESULT_OK) {
            data?.getParcelableArrayListExtra<ImageItem>(ImagePreviewActivity.RESULT_UPDATED_SELECTED_IMAGES)
                ?.let { updatedSelectedList ->
                    // 使用预览后更新的选中列表
                    selectedImages.clear()
                    selectedImages.addAll(updatedSelectedList)

                    // 更新UI
                    adapter.notifyDataSetChanged() // 刷新 GridView 的选中状态
                    updateDoneButtonState() // 更新完成按钮的状态
                }
        }
    }

    override fun onCameraIconClick() {
        openCamera()
    }

    private fun initLaunchers() {
        requestPermissionLauncher =
            registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
                val readPermissionGranted =
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                        permissions[Manifest.permission.READ_MEDIA_IMAGES] ?: false
                    } else {
                        permissions[Manifest.permission.READ_EXTERNAL_STORAGE] ?: false
                    }

                if (readPermissionGranted) {
                    loadImagesFromGallery()
                } else {
                    Toast.makeText(this, "读取存储权限被拒绝，无法选择图片", Toast.LENGTH_LONG)
                        .show()
                    // 可以关闭 Activity 或提示用户去设置中开启权限
                }


                var allRequiredPermissionsGranted = true
                var cameraPermissionGranted = false // 单独跟踪相机权限状态
                var readStoragePermissionGranted = false
                var writeStoragePermissionGrantedOnOldSdk =
                    Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q // 在Q+上，我

                permissions.entries.forEach { entry ->
                    Log.d("ImagePicker", "权限回调: ${entry.key}, 状态: ${entry.value}")
                    when (entry.key) {
                        Manifest.permission.CAMERA -> cameraPermissionGranted = entry.value
                        Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_EXTERNAL_STORAGE -> readStoragePermissionGranted =
                            entry.value

                        Manifest.permission.WRITE_EXTERNAL_STORAGE -> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) writeStoragePermissionGrantedOnOldSdk =
                            entry.value
                    }
                }


                // 更新权限检查逻辑，以决定是否加载图片
                // 主要依赖读取权限和相机权限（如果需要）
                if (readStoragePermissionGranted && (cameraPermissionGranted || !showCameraButtonConfig)) {
                    Log.d("ImagePicker", "读取和相机（如果需要）权限已获取，加载图片。")
                    loadImagesFromGallery()
                    // 如果 writeStoragePermissionGrantedOnOldSdk 为 false，你可以在需要写入公共目录时再单独处理或提示
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q && !writeStoragePermissionGrantedOnOldSdk) {
                        Toast.makeText(
                            this,
                            "未授予写入存储权限，部分保存功能可能受限",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                } else {
                    Toast.makeText(this, "部分必要权限被拒绝", Toast.LENGTH_SHORT).show()
                    if (!readStoragePermissionGranted) {
                        Log.d("ImagePicker", "读取存储权限被拒绝，无法加载图片。")
                        // 可以关闭 Activity 或显示错误信息
                    }
                }
            }
        // 注意：createImageFileAndUri 如果总是写入 getExternalFilesDir()，它本身不需要 WRITE_EXTERNAL_STORAGE
        // openCamera 中的逻辑，特别是 Android Q+ 使用 MediaStore API 保存到公共目录时，也不需要 WRITE_EXTERNAL_STORAGE

        takePictureLauncher =
            registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
                Log.d(
                    "ImagePicker",
                    "[${this.hashCode()}] takePictureLauncher callback. Success: $success"
                )
                // 打印ViewModel中的原始状态
                Log.d(
                    "ImagePicker",
                    "[${this.hashCode()}] takePictureLauncher - VM.file: ${viewModel.cameraImageFile?.absolutePath}, VM.uri: ${viewModel.cameraImageUri}"
                )

                if (success) {
                    val currentImageUriFromViewModel = viewModel.cameraImageUri // 这个应该是有效的
                    val currentImageFileFromViewModel = viewModel.cameraImageFile // 这个在Q+时会是null

                    if (currentImageUriFromViewModel != null) {
                        // 情况1：Android Q+ (使用 MediaStore Uri，currentImageFileFromViewModel 为 null)
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && currentImageFileFromViewModel == null) {
                            Log.d("ImagePicker", "照片处理 (Q+): Uri=$currentImageUriFromViewModel")
                            // 对于 MediaStore Uri，我们没有直接的 File 对象。
                            // MediaStore Uri 本身就可以用来加载图片。
                            // 如果需要文件路径（例如给Luban），需要从这个 MediaStore Uri 查询 MediaStore.Images.Media.DATA
                            // 或者，如果Luban可以直接处理InputStream，可以从Uri获取InputStream

                            // 1. 获取文件路径（如果需要）
                            var mediaStorePath: String? = null
                            try {
                                applicationContext.contentResolver.query(
                                    currentImageUriFromViewModel,
                                    arrayOf(MediaStore.Images.Media.DATA),
                                    null,
                                    null,
                                    null
                                )?.use { cursor ->
                                    if (cursor.moveToFirst()) {
                                        mediaStorePath =
                                            cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA))
                                        Log.d(
                                            "ImagePicker",
                                            "MediaStore Path (Q+): $mediaStorePath"
                                        )
                                    }
                                }
                            } catch (e: Exception) {
                                Log.e("ImagePicker", "从MediaStore Uri获取路径失败 (Q+)", e)
                            }

                            // 即使mediaStorePath获取失败或为null，currentImageUriFromViewModel仍然是有效的
                            val newImageItem = ImageItem(
                                id = System.currentTimeMillis(),
                                uri = currentImageUriFromViewModel, // 直接使用MediaStore的Uri
                                path = mediaStorePath, // 可能为null，Luban需要处理这种情况
                                isSelected = false
                            )

                            lifecycleScope.launch(Dispatchers.Main) {
                                Toast.makeText(
                                    this@ImagePickerActivity,
                                    "照片已拍摄 (Q+)",
                                    Toast.LENGTH_SHORT
                                ).show()
                                val currentList = adapter.getImages().toMutableList()
                                currentList.add(0, newImageItem)
                                adapter.updateImages(currentList)
                            }
                            // 对于MediaStore直接创建的图片，MediaStore已经知道了，通常不需要再次扫描
                            // 但如果想确保其他应用也能立即看到，扫描一下也无妨
                            if (mediaStorePath != null) {
                                MediaScannerConnection.scanFile(
                                    this,
                                    arrayOf(mediaStorePath),
                                    arrayOf("image/jpeg")
                                ) { path, scannedUri ->
                                    Log.d(
                                        "ImagePicker",
                                        "媒体库扫描完成 (Q+): $path -> $scannedUri"
                                    )
                                }
                            } else {
                                Log.w(
                                    "ImagePicker",
                                    "MediaStore Path (Q+) 未获取到，无法精确扫描，但图片应已在MediaStore中。"
                                )
                            }

                        }
                        // 情况2：Android P及以下 (使用 FileProvider Uri，currentImageFileFromViewModel 应该有效)
                        else if (currentImageFileFromViewModel != null && currentImageFileFromViewModel.exists()) {
                            val newPhotoFile = currentImageFileFromViewModel
                            val newPhotoUri = currentImageUriFromViewModel // 这个Uri是FileProvider的Uri
                            val newPhotoPath = newPhotoFile.absolutePath

                            Log.d(
                                "ImagePicker",
                                "照片处理 (P-): Uri=$newPhotoUri, Path=$newPhotoPath"
                            )

                            val newImageItem = ImageItem(
                                System.currentTimeMillis(),
                                newPhotoUri,
                                newPhotoPath,
                                false
                            )
                            lifecycleScope.launch(Dispatchers.Main) {
                                Toast.makeText(
                                    this@ImagePickerActivity,
                                    "照片已拍摄 (P-)",
                                    Toast.LENGTH_SHORT
                                ).show()
                                val currentList = adapter.getImages().toMutableList()
                                currentList.add(0, newImageItem)
                                adapter.updateImages(currentList)
                            }
                            MediaScannerConnection.scanFile(
                                this,
                                arrayOf(newPhotoPath),
                                arrayOf("image/jpeg")
                            ) { path, scannedUri ->
                                Log.d("ImagePicker", "媒体库扫描完成 (P-): $path -> $scannedUri")
                            }
                        }
                        // 异常情况：Uri有效，但File对象无效（不应该发生在P-分支）或版本判断与File对象状态不符
                        else {
                            Log.e(
                                "ImagePicker", "拍照成功，但文件引用状态异常。" +
                                        " File is null: ${currentImageFileFromViewModel == null}," +
                                        " File exists: ${currentImageFileFromViewModel?.exists()}," +
                                        " Uri is: $currentImageUriFromViewModel, BuildVersion: ${Build.VERSION.SDK_INT}"
                            )
                            Toast.makeText(this, "保存照片时状态异常", Toast.LENGTH_LONG).show()
                        }

                    } else { // currentImageUriFromViewModel 为 null，这本身就是个问题
                        Log.e("ImagePicker", "拍照成功，但 ViewModel 中的 Uri 引用丢失。")
                        Toast.makeText(this, "保存照片时出错 (Uri丢失)", Toast.LENGTH_LONG).show()
                    }
                } else {
                    Toast.makeText(this, "拍照已取消", Toast.LENGTH_SHORT).show()
                }
                // 清理 ViewModel，确保下次拍照状态干净
                viewModel.cameraImageFile = null
                viewModel.cameraImageUri = null
                Log.d(
                    "ImagePicker",
                    "ViewModel Cleared: File=${viewModel.cameraImageFile}, Uri=${viewModel.cameraImageUri}"
                )
            }
    }

    private fun hasStoragePermission(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_MEDIA_IMAGES
            ) == PackageManager.PERMISSION_GRANTED
        } else {
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        }
    }

    private fun hasCameraPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun hasWriteStoragePermission(): Boolean {
        // 对于 Android Q (API 29) 及以上，如果应用适配了作用域存储，
        // 访问公共目录通过 MediaStore API，通常不需要 WRITE_EXTERNAL_STORAGE。
        // 对于应用私有目录，始终不需要此权限。
        // 此检查主要针对需要直接写入外部公共存储的旧版 Android 或未适配作用域存储的情况。
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // 在 Q+ 上，通常不需要这个权限来写公共目录（用 MediaStore）
            // 如果你的应用 targetSdkVersion < 29，或者设置了 requestLegacyExternalStorage=true，则行为可能不同
            true // 假设在 Q+ 通过 MediaStore 操作，或者认为不需要显式请求
        } else {
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        }
    }


    private fun setupPermissions() {
        val permissionsToRequest = mutableListOf<String>()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_MEDIA_IMAGES
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsToRequest.add(Manifest.permission.READ_MEDIA_IMAGES)
            }
        } else {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsToRequest.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }

        if (showCameraButtonConfig) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.CAMERA
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsToRequest.add(Manifest.permission.CAMERA)
                Log.d("ImagePicker", "相机权限将被请求 (如果未授予)")
            }
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { // 只在 Android P (API 28)及以下版本检查并请求
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                permissionsToRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                Log.d(
                    "ImagePicker",
                    "WRITE_EXTERNAL_STORAGE permission will be requested (for API < Q)"
                )
            }
        }

        Log.d("ImagePicker", "需要请求的权限列表: $permissionsToRequest")

        if (permissionsToRequest.isNotEmpty()) {
            Log.d("ImagePicker", "正在启动权限请求弹窗...")
            requestPermissionLauncher.launch(permissionsToRequest.toTypedArray())
        } else {
            Log.d("ImagePicker", "所有必要的权限都已授予，直接加载图片。")
            loadImagesFromGallery()
        }
    }

    private fun openCamera() {
        if (!hasCameraPermission()) {
            Log.d("ImagePicker", "尝试打开相机，但无权限，再次请求。")
            // 明确地只请求相机权限，如果它之前被拒绝了
            requestPermissionLauncher.launch(arrayOf(Manifest.permission.CAMERA))
            // Toast.makeText(this, "需要相机权限才能拍照", Toast.LENGTH_SHORT).show() // 这个提示可以在权限回调中处理
            return
        }

        lifecycleScope.launch {
            var uriToLaunch: Uri? = null
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                viewModel.cameraImageFile = null // 明确在Q+时，我们不依赖ViewModel中的File对象来判断
                viewModel.cameraImageUri = createImageUriForCameraOnQPlus()
                uriToLaunch = viewModel.cameraImageUri
                Log.d(
                    "ImagePicker",
                    "[${this.hashCode()}] openCamera (Q+) - VM.file set to null, VM.uri set: ${viewModel.cameraImageUri}"
                )
            } else {
                val imageOutput = createImageFileForCameraOnPMinus() // 您的旧方法 (P及以下)
                if (imageOutput != null) {
                    viewModel.cameraImageFile = imageOutput.first
                    viewModel.cameraImageUri = imageOutput.second
                    uriToLaunch = viewModel.cameraImageUri
                    Log.d(
                        "ImagePicker",
                        "[${this.hashCode()}] openCamera (P-) - VM.file set: ${viewModel.cameraImageFile?.absolutePath}, VM.uri set: ${viewModel.cameraImageUri}"
                    )
                }
            }

            if (uriToLaunch != null) {
                takePictureLauncher.launch(uriToLaunch)
            } else {
                Log.w("ImagePicker", "openCamera - uriToLaunch is null. Not launching camera.")
                Toast.makeText(
                    this@ImagePickerActivity,
                    "无法创建图片文件用于拍照",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }

    }

    // 修改 createImageUri 为 createImageFileAndUri，同时返回 File 和 Uri
    private fun createImageFileAndUri(): Pair<File, Uri>? { // <--- 修改返回类型
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val imageFileName = "JPEG_${timeStamp}_"
        val storageDir: File? = getExternalFilesDir("Pictures")

        if (storageDir == null) {
            Log.e("ImagePicker", "外部文件目录 'Pictures' 不可用。")
            Toast.makeText(this, "无法访问存储目录以创建图片", Toast.LENGTH_LONG).show()
            return null
        }

        if (!storageDir.exists()) {
            if (!storageDir.mkdirs()) {
                Log.e("ImagePicker", "无法创建图片存储目录: ${storageDir.absolutePath}")
                Toast.makeText(this, "无法创建图片存储目录", Toast.LENGTH_LONG).show()
                return null
            }
        }

        return try {
            val imageFile = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
            )
            val authority = "${applicationContext.packageName}.fileprovider"
            val imageUri = FileProvider.getUriForFile(
                this,
                authority,
                imageFile
            )
            Log.d(
                "ImagePicker",
                "FileProvider authority: $authority, File: ${imageFile.absolutePath}, Uri: $imageUri"
            )
            Pair(imageFile, imageUri) // <--- 返回 File 和 Uri
        } catch (e: Exception) {
            Log.e("ImagePicker", "创建图片 File 和 URI 时发生错误", e)
            Toast.makeText(this, "创建图片文件失败: ${e.message}", Toast.LENGTH_LONG).show()
            null
        }
    }


    private fun getPathFromUri(context: Context, uri: Uri): String? {
        // 这个方法在处理 content URI（尤其是来自 FileProvider 的）转换为绝对路径时可能不可靠或不必要
        // Luban 可以直接处理 File 对象，而我们通过 cameraImageUri?.path 应该能拿到创建时的路径
        // 如果是从 MediaStore 加载的图片，其 DATA 字段通常是可靠的（但在 Android Q+ 需要注意作用域存储）
        if ("file".equals(uri.scheme, ignoreCase = true)) {
            return uri.path
        }
        if ("content".equals(uri.scheme, ignoreCase = true)) {
            try {
                context.contentResolver.query(
                    uri,
                    arrayOf(MediaStore.Images.Media.DATA),
                    null,
                    null,
                    null
                )?.use { cursor ->
                    if (cursor.moveToFirst()) {
                        val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                        return cursor.getString(columnIndex)
                    }
                }
            } catch (e: Exception) {
                Log.w("ImagePicker", "从 Content URI 获取路径失败: $uri", e)
            }
        }
        // 对于 FileProvider 的 URI，直接获取路径通常不被推荐，应该通过 File 对象操作
        // 如果 cameraImageUri 的 path 是 null，这里也可能返回 null
        return null
    }


    private fun loadImagesFromGallery() {
        if (!hasStoragePermission()) {
            Log.w("ImagePicker", "尝试加载相册但无存储权限。")
            // 可以在这里提示用户需要存储权限，或者在 setupPermissions 失败后处理
            return
        }
        Log.d("ImagePicker", "开始加载相册图片...")
        lifecycleScope.launch(Dispatchers.IO) {
            val imageList = mutableListOf<ImageItem>()
            val projection = arrayOf(
                MediaStore.Images.Media._ID,        // 图片的唯一ID
                MediaStore.Images.Media.DISPLAY_NAME, // 图片显示名称
                MediaStore.Images.Media.DATA,       // 图片的绝对文件路径
                MediaStore.Images.Media.DATE_ADDED  // 图片添加日期，用于排序
            )
            // 查询所有外部存储中的图片，按添加日期降序排列
            val queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            val sortOrder = "${MediaStore.Images.Media.DATE_ADDED} DESC"

            try {
                contentResolver.query(queryUri, projection, null, null, sortOrder)?.use { cursor ->
                    Log.d("ImagePicker", "查询到图片数量: ${cursor.count}")
                    val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
                    val pathColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                    // val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME) // 如果需要文件名

                    while (cursor.moveToNext()) {
                        val id = cursor.getLong(idColumn)
                        val path = cursor.getString(pathColumn) // 这个路径对Luban很有用
                        val contentUri =
                            Uri.withAppendedPath(queryUri, id.toString()) // 构建Content URI
                        Log.d("ImageUri", "Content URI: $contentUri  path: $path")
                        imageList.add(ImageItem(id, contentUri, path))
                    }
                }
            } catch (e: Exception) {
                Log.e("ImagePicker", "加载相册图片时出错", e)
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@ImagePickerActivity, "加载图片失败", Toast.LENGTH_SHORT)
                        .show()
                }
            }

            withContext(Dispatchers.Main) {
                Log.d("ImagePicker", "图片加载完成，更新UI，数量: ${imageList.size}")
                adapter.updateImages(imageList)
            }
        }
    }

    private fun handleImageSelection(imageItem: ImageItem, isSelected: Boolean) {
        val currentSelectionCount = selectedImages.count { it.id == imageItem.id }

        if (isSelected) {
            if (selectedImages.size < maxSelectionCount) {
                if (currentSelectionCount == 0) { // 防止重复添加
                    selectedImages.add(imageItem)
                }
            } else {
                if (currentSelectionCount == 0) { // 只有当尝试选择新图片且已达上限时才提示并阻止
                    Toast.makeText(this, "最多选择 $maxSelectionCount 张图片", Toast.LENGTH_SHORT)
                        .show()
                    // 更新UI，确保该项不被勾选 (Adapter内部的点击逻辑会处理)
                    adapter.notifyDataSetChanged() // 或者更精确的刷新
                    return
                }
            }
        } else {
            selectedImages.removeAll { it.id == imageItem.id }
        }
        updateDoneButtonState()
        adapter.notifyDataSetChanged() // 更新Adapter以反映选中状态的变化
    }

    private fun updateDoneButtonState() {
        val count = selectedImages.size
        if (count > 0) {
            doneButton.text = "完成($count/$maxSelectionCount)"
            doneButton.isEnabled = true
            previewButton.text = "预览($count)"
            previewButton.visibility = View.VISIBLE
        } else {
            doneButton.text = "完成"
            doneButton.isEnabled = false
            previewButton.text = "预览"
            previewButton.visibility = View.GONE
        }
    }

    private fun processAndReturnSelectedImages() {
        if (selectedImages.isEmpty()) {
            setResult(Activity.RESULT_CANCELED)
            finish()
            return
        }

        doneButton.isEnabled = false
        Toast.makeText(this, "处理中...", Toast.LENGTH_SHORT).show()

        lifecycleScope.launch {
            val originalUris = ArrayList(selectedImages.map { it.uri })
            val compressedFilePaths = ArrayList<String>()

            if (enableLubanCompress) {
                val filesToCompress = mutableListOf<File>()
                val tempFilesCreatedForLuban = mutableListOf<File>() // 用于跟踪临时文件

                for (imageItem in selectedImages) {
                    var fileForLuban: File? = null
                    try {
                        // 优先尝试直接使用 ImageItem.path (如果存在且可访问)
                        // 这对于应用自己创建的文件（如拍照后保存到私有目录）或旧版 Android 可能有效
                        if (imageItem.path != null) {
                            val potentialFile = File(imageItem.path)
                            if (potentialFile.exists() && potentialFile.canRead()) {
                                fileForLuban = potentialFile
                                Log.d(
                                    "ImagePicker",
                                    "使用 ImageItem.path 进行压缩: ${imageItem.path}"
                                )
                            }
                        }

                        // 如果 ImageItem.path 无效或不可访问（特别是对于 Android 10+ 的 MediaStore 文件）
                        // 则尝试通过 ContentResolver 将 Content URI 的内容复制到一个临时文件中
                        if (fileForLuban == null) {
                            Log.d(
                                "ImagePicker",
                                "ImageItem.path 无效或不可读，尝试从 Uri 复制到临时文件: ${imageItem.uri}"
                            )
                            val tempFile = createTempFileFromUri(applicationContext, imageItem.uri)
                            if (tempFile != null) {
                                fileForLuban = tempFile
                                tempFilesCreatedForLuban.add(tempFile) // 添加到列表以便后续删除
                                Log.d(
                                    "ImagePicker",
                                    "已将 Uri 内容复制到临时文件: ${tempFile.absolutePath}"
                                )
                            } else {
                                Log.e(
                                    "ImagePicker",
                                    "无法从 Uri 创建临时文件进行压缩: ${imageItem.uri}"
                                )
                                // 跳过这个文件，或者也可以将原始文件路径加入（如果允许不压缩）
                                continue
                            }
                        }

                        if (fileForLuban != null) {
                            filesToCompress.add(fileForLuban)
                        }

                    } catch (e: SecurityException) {
                        Log.e(
                            "ImagePicker",
                            "尝试访问文件进行压缩时发生安全异常 (Uri: ${imageItem.uri}, Path: ${imageItem.path})",
                            e
                        )
                        // 提示用户权限问题或文件不可访问
                        withContext(Dispatchers.Main) {
                            Toast.makeText(
                                this@ImagePickerActivity,
                                "压缩图片 ${imageItem.uri.lastPathSegment} 失败：权限不足或文件不可访问",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                        continue // 继续处理下一个文件
                    } catch (e: Exception) {
                        Log.e(
                            "ImagePicker",
                            "处理待压缩文件 ${imageItem.uri.lastPathSegment} 时发生错误",
                            e
                        )
                        continue
                    }
                }

                if (filesToCompress.isNotEmpty()) {
                    Log.d("ImagePicker", "准备压缩文件数量: ${filesToCompress.size}")
                    try {
                        val compressedFiles =
                            compressWithLubanAsync(this@ImagePickerActivity, filesToCompress)
                        compressedFiles.forEach { file ->
                            compressedFilePaths.add(file.absolutePath)
                        }
                        Log.d("ImagePicker", "压缩完成，数量: ${compressedFiles.size}")
                    } catch (e: Exception) {
                        Log.e("ImagePicker", "Luban 压缩批处理错误或协程取消", e)
                        withContext(Dispatchers.Main) {
                            Toast.makeText(
                                this@ImagePickerActivity,
                                "图片压缩失败: ${e.message}",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                } else if (selectedImages.isNotEmpty()) { // 有选中的图片，但没有一个能准备好用于压缩
                    Log.w("ImagePicker", "没有有效的文件可用于压缩。")
                    withContext(Dispatchers.Main) {
                        Toast.makeText(
                            this@ImagePickerActivity,
                            "部分图片无法准备用于压缩",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }

                // 清理为Luban创建的临时文件
                tempFilesCreatedForLuban.forEach { it.delete() }
                Log.d(
                    "ImagePicker",
                    "已清理 ${tempFilesCreatedForLuban.size} 个为Luban创建的临时文件。"
                )

            } else { // 如果不启用压缩，可以考虑直接返回原始文件的路径（如果可获取）或URI
                // selectedImages.forEach { item -> item.path?.let { originalFilePaths.add(it) } }
                // 或者直接返回原始URI列表，让调用者处理
            }


            val resultIntent = Intent().apply {
                putParcelableArrayListExtra(RESULT_PICKED_IMAGES, originalUris)
                if (compressedFilePaths.isNotEmpty()) {
                    putStringArrayListExtra(RESULT_COMPRESSED_IMAGES, compressedFilePaths)
                }
                // 如果 enableLubanCompress 为 false，或者所有文件都压缩失败但仍希望返回结果，
                // 你可能需要决定 RESULT_COMPRESSED_IMAGES 中放什么，或者增加一个标志位。
            }
            setResult(Activity.RESULT_OK, resultIntent)
            finish()
        }
    }

    /**
     * 辅助函数：从 Content URI 复制内容到应用的缓存目录下的一个临时文件
     * @param context 上下文
     * @param uri 要复制内容的源 URI
     * @return 成功则返回创建的临时 File 对象，失败则返回 null
     */
    private fun createTempFileFromUri(context: Context, uri: Uri): File? {
        var inputStream: InputStream? = null
        var fileOutputStream: FileOutputStream? = null
        var tempFile: File? = null

        try {
            inputStream = context.contentResolver.openInputStream(uri)
            if (inputStream == null) {
                Log.e("ImagePicker", "无法为 URI 打开输入流: $uri")
                return null
            }

            // 从URI尝试获取一个合理的文件名，如果获取不到则生成一个时间戳文件名
            val fileName = getFileNameFromUri(context, uri) ?: "temp_image_for_luban_${System.currentTimeMillis()}.jpg"
            tempFile = File(context.cacheDir, fileName) // 在应用缓存目录创建临时文件
            // tempFile.createNewFile() // FileOutputStream 会自动创建文件，如果需要确保目录存在，可以检查 context.cacheDir.exists()

            fileOutputStream = FileOutputStream(tempFile)
            val buffer = ByteArray(4 * 1024) // 4KB 缓冲
            var read: Int
            while (inputStream.read(buffer).also { read = it } != -1) {
                fileOutputStream.write(buffer, 0, read)
            }
            fileOutputStream.flush() // 确保所有数据写入文件

            Log.d("ImagePicker", "成功从 Uri 复制到临时文件: ${tempFile.absolutePath}")
            return tempFile
        } catch (e: Exception) { // 捕获更广泛的异常，因为文件操作可能抛出多种异常
            Log.e("ImagePicker", "从 Uri 复制到临时文件失败 (Uri: $uri)", e)
            tempFile?.delete() // 如果部分创建了文件，尝试删除它
            return null
        } finally {
            try {
                inputStream?.close()
            } catch (e: Exception) {
                Log.e("ImagePicker", "关闭输入流时出错", e)
            }
            try {
                fileOutputStream?.close()
            } catch (e: Exception) {
                Log.e("ImagePicker", "关闭输出流时出错", e)
            }
        }
    }

    /**
     * 辅助函数：尝试从 Content URI 获取文件名
     * @param context 上下文
     * @param uri Content URI
     * @return 文件名字符串，如果无法获取则返回 null
     */
    private fun getFileNameFromUri(context: Context, uri: Uri): String? {
        var fileName: String? = null
        if (uri.scheme == "content") {
            try {
                context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
                    if (cursor.moveToFirst()) {
                        val displayNameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                        if (displayNameIndex != -1) {
                            fileName = cursor.getString(displayNameIndex)
                        }
                    }
                }
            } catch (e: Exception) {
                Log.w("ImagePicker", "从 Uri 获取 DISPLAY_NAME 失败 (Uri: $uri)", e)
            }
        }
        // 如果无法从 ContentResolver 获取 DisplayName，尝试从路径的最后一部分获取
        if (fileName == null) {
            fileName = uri.lastPathSegment
        }
        // 对于某些URI，lastPathSegment 可能包含特殊字符或不是一个有效的文件名
        // 可以根据需要进一步清理 fileName
        return fileName
    }

    private suspend fun compressWithLubanAsync(context: Context, photos: List<File>): List<File> =
        suspendCancellableCoroutine { continuation ->
            if (photos.isEmpty()) {
                if (continuation.isActive) continuation.resume(emptyList())
                return@suspendCancellableCoroutine
            }

            val compressedFiles = mutableListOf<File>()
            var successfulCompressions = 0
            var failedCompressions = 0
            val totalFiles = photos.size

            val listener = object : OnCompressListener {
                override fun onStart() {
                    Log.d("Luban", "开始压缩一批")
                }

                override fun onSuccess(file: File) {
                    compressedFiles.add(file)
                    successfulCompressions++
                    checkCompletion()
                }

                override fun onError(e: Throwable) {
                    Log.e("Luban", "压缩单个文件失败: ${e.message}")
                    failedCompressions++
                    checkCompletion()
                }

                private fun checkCompletion() {
                    if (successfulCompressions + failedCompressions == totalFiles) {
                        if (continuation.isActive) {
                            // 如果需要，可以在这里检查 failedCompressions 的数量
                            continuation.resume(compressedFiles)
                        }
                    }
                }
            }

            val targetDirFile = File(getLubanTargetPath(context))
            if (!targetDirFile.exists()) {
                targetDirFile.mkdirs()
            }

            Log.d("Luban", "Luban 目标目录: ${targetDirFile.absolutePath}")
            photos.forEach {
                Log.d("Luban", "尝试压缩: ${it.absolutePath}, 大小: ${it.length() / 1024}KB")
            }


            Luban.with(context)
                .load(photos)
                .ignoreBy(100) // kb
                .setTargetDir(targetDirFile.absolutePath)
                .setCompressListener(listener)
                .launch()

            continuation.invokeOnCancellation {
                Log.d("ImagePicker", "Luban 压缩协程已取消。")
            }
        }

    private fun getLubanTargetPath(context: Context): String {
        val path = File(context.cacheDir, "luban_compress")
        if (!path.exists()) {
            path.mkdirs()
        }
        return path.absolutePath
    }

    private fun saveImageToPublicPictures(bitmap: Bitmap, displayName: String): Uri? {
        val resolver = applicationContext.contentResolver
        val imageCollection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        } else {
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        }

        val imageDetails = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, displayName)
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(MediaStore.Images.Media.IS_PENDING, 1) // 先标记为待处理
                put(
                    MediaStore.Images.Media.RELATIVE_PATH,
                    Environment.DIRECTORY_PICTURES + "/Test_Demo"
                ) // 可选子目录
            }
        }

        var imageUri: Uri? = null
        try {
            imageUri = resolver.insert(imageCollection, imageDetails)
            imageUri?.let { uri ->
                resolver.openOutputStream(uri)?.use { outputStream ->
                    if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 95, outputStream)) {
                        Log.e("ImagePicker", "无法将 Bitmap 压缩到输出流")
                        // 可能需要删除部分创建的条目
                        resolver.delete(uri, null, null)
                        imageUri = null
                    }
                }
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    imageDetails.clear()
                    imageDetails.put(MediaStore.Images.Media.IS_PENDING, 0) // 标记为处理完成
                    resolver.update(uri, imageDetails, null, null)
                }
            }
        } catch (e: Exception) {
            Log.e("ImagePicker", "保存图片到公共目录失败", e)
            imageUri?.let { resolver.delete(it, null, null) } // 出错时尝试删除
            imageUri = null
        }
        return imageUri
    }

    private fun createImageUriForCameraOnQPlus(): Uri? {
        val resolver = applicationContext.contentResolver
        val imageCollection =
            MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val imageFileName = "JPEG_${timeStamp}_"

        val imageDetails = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, "$imageFileName.jpg")
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            // DIRECTORY_PICTURES 或 DIRECTORY_DCIM/YourAppName
            put(
                MediaStore.Images.Media.RELATIVE_PATH,
                Environment.DIRECTORY_PICTURES + File.separator + "YourAppName"
            )
            // IS_PENDING 标志不是必须的，但如果后续有处理可以加上然后清除
        }
        return try {
            resolver.insert(imageCollection, imageDetails)
        } catch (e: Exception) {
            Log.e("ImagePicker", "为相机创建 MediaStore Uri 失败", e)
            null
        }
    }

    private fun createImageFileForCameraOnPMinus(): Pair<File, Uri>? {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // 如果没有权限，应该在拍照前请求
            Toast.makeText(this, "需要存储权限以保存照片到公共目录", Toast.LENGTH_LONG).show()
            // 这里可以触发权限请求，或者在 openCamera 的开头检查并请求
            return null
        }

        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val imageFileName = "JPEG_${timeStamp}_"
        // 获取公共的 Pictures 目录
        val storageDir =
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/Test_Demo")

        if (!storageDir.exists()) {
            if (!storageDir.mkdirs()) {
                Log.e("ImagePicker", "无法创建公共图片存储目录: ${storageDir.absolutePath}")
                return null
            }
        }

        return try {
            val imageFile = File(storageDir, "$imageFileName.jpg")
            val imageUri = FileProvider.getUriForFile(
                this,
                "${applicationContext.packageName}.fileprovider",
                imageFile
            )
            Pair(imageFile, imageUri)
        } catch (e: Exception) {
            Log.e("ImagePicker", "为相机创建公共图片 File 和 URI 时发生错误", e)
            null
        }
    }

    // 辅助函数，尝试从FileProvider的URI获取原始路径 (不推荐作为常规使用)
    private fun getPathFromContentUriForFileProvider(context: Context, uri: Uri): String? {
        if ("content".equals(uri.scheme) && uri.authority == "${context.packageName}.fileprovider") {
            // FileProvider URI的路径段通常是 /<name_in_paths_xml>/<actual_file_path_relative_to_root_in_paths_xml>
            // 例如： content://com.example.app.fileprovider/my_images/Pictures/image.jpg
            // getPath() 返回: /my_images/Pictures/image.jpg
            // 我们需要找到 File(getExternalFilesDir(null), uri.path.substringAfter(FIRST_PATH_SEGMENT_FROM_XML))
            // 这很复杂且依赖于你的 file_paths.xml 配置，这里只做最简单的假设
            // 这个方法非常粗略，不健壮！
            val pathSegment =
                uri.pathSegments.drop(1).joinToString(File.separator) // 跳过第一个路径段（如"my_images"）
            // 假设你的 file_paths.xml 中的 <external-files-path name="my_images" path="Pictures" />
            // 那么根目录是 getExternalFilesDir(null)
            val rootDir =
                context.getExternalFilesDir(null) // 或者 getExternalFilesDir("Pictures") 的父目录
            if (rootDir != null) {
                // 如果 path="Pictures" 在 XML 中，而你用 getExternalFilesDir("Pictures") 做根，那么上面 drop(1) 可能不适用
                // 或者你需要知道你在 createTempFile 时用的 storageDir 是什么
                // 假设 uri.path 的第一段是你在xml中定义的 name，后面的是相对于 path 的路径
                // 比如 storageDir = getExternalFilesDir("Pictures")
                // xml: <external-files-path name="my_pics" path="Pictures" />
                // File.createTempFile("JPEG_", ".jpg", storageDir) -> /storage/emulated/0/Android/data/pkg/files/Pictures/JPEG_123.jpg
                // Uri: content://pkg.fileprovider/my_pics/JPEG_123.jpg
                // uri.pathSegments -> ["my_pics", "JPEG_123.jpg"]
                // 我们需要组合 storageDir 和 "JPEG_123.jpg"

                // 这是一个非常非常粗略的示例，不要在生产中使用!
                if (uri.pathSegments.size > 1) {
                    val fileName = uri.pathSegments.last()
                    // 假设你知道原始的 storageDir (比如 getExternalFilesDir(Environment.DIRECTORY_PICTURES))
                    val assumedStorageDir =
                        context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
                    if (assumedStorageDir != null) {
                        val potentialFile = File(assumedStorageDir, fileName)
                        if (potentialFile.exists()) return potentialFile.absolutePath
                    }
                }
            }
        }
        return null
    }

    fun onSaveToPublicGalleryClicked() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { // 只在旧版系统上关注这个权限
            if (hasWriteStoragePermission()) {
                // 执行保存到公共相册的操作 (Android P 及以下版本)
//                saveImageToPublicPictures()
            } else {
                // 提示用户需要权限，或者再次触发权限请求
                Toast.makeText(this, "需要写入存储权限以保存到公共相册", Toast.LENGTH_SHORT).show()
                // 可以考虑再次调用 requestPermissionLauncher.launch(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE))
                // 但更好的做法是在 setupPermissions 时就请求好，或者引导用户去设置页开启
            }
        } else {
            // 对于 Android Q+，使用 MediaStore API 保存到公共相册，通常不需要这个权限
//            saveImageToPublicPictures()
        }
    }

    fun isUriValid(context: Context, uri: Uri): Boolean {
        var inputStream: InputStream? = null
        return try {
            inputStream = context.contentResolver.openInputStream(uri)
            inputStream != null // If openInputStream doesn't throw and returns non-null, it's likely valid
        } catch (e: Exception) {
            // FileNotFoundException or other exceptions mean it's not accessible
            Log.e("ImagePicker", "Failed to open URI: $uri", e)
            false
        } finally {
            inputStream?.close()
        }
    }

    fun copyUriToTempFile(context: Context, uri: Uri): File? {
        var inputStream: InputStream? = null
        var fileOutputStream: FileOutputStream? = null
        var tempFile: File? = null

        try {
            inputStream = context.contentResolver.openInputStream(uri)
            if (inputStream == null) {
                Log.e("ImagePicker", "Failed to open input stream for URI: $uri")
                return null
            }

            // Create a temporary file in the app's cache directory
            val fileName = getFileName(context, uri) ?: "temp_image_${System.currentTimeMillis()}"
            tempFile = File(context.cacheDir, fileName)
            tempFile.createNewFile() // Ensure the file exists

            fileOutputStream = FileOutputStream(tempFile)
            val buffer = ByteArray(4 * 1024) // 4K buffer
            var read: Int
            while (inputStream.read(buffer).also { read = it } != -1) {
                fileOutputStream.write(buffer, 0, read)
            }
            fileOutputStream.flush()
            Log.d("ImagePicker", "Successfully copied URI to temp file: ${tempFile.absolutePath}")
            return tempFile
        } catch (e: Exception) { // Catch a broader exception initially for logging
            // The FileNotFoundException from your log would be caught here if it's during openInputStream
            Log.e("ImagePicker", "Error copying URI to temp file (Uri: $uri)", e)
            tempFile?.delete() // Clean up if partially created
            return null
        } finally {
            try {
                inputStream?.close()
            } catch (e: Exception) {
                Log.e("ImagePicker", "Error closing input stream", e)
            }
            try {
                fileOutputStream?.close()
            } catch (e: Exception) {
                Log.e("ImagePicker", "Error closing output stream", e)
            }
        }
    }

    // Helper to try and get a filename from the URI
    fun getFileName(context: Context, uri: Uri): String? {
        var fileName: String? = null
        if (uri.scheme == "content") {
            context.contentResolver.query(uri, null, null, null, null)?.use { cursor ->
                if (cursor.moveToFirst()) {
                    val displayNameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                    if (displayNameIndex != -1) {
                        fileName = cursor.getString(displayNameIndex)
                    }
                }
            }
        }
        if (fileName == null) {
            fileName = uri.lastPathSegment
        }
        return fileName
    }
}
